import 'package:dmz/tools/map/map_approval_number.dart';
import 'package:dmz/tools/map/map_location.dart';
import 'package:dmz/tools/map/map_manger.dart';
import 'package:flutter/cupertino.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';

class EMIGDMapWidget extends StatefulWidget {
  final LatLng? latLng; //初始化位置
  final void Function(AMapController controller)? onMapCreated; //控制器回调
  final Map<String, Marker>? initMarkerMap; //标记点
  final Map<String, Polyline>? initPolylinesMap; //轨迹
  final Function(double latitude, double longitude)? selfLocationBack;
  const EMIGDMapWidget(
      {super.key,
      this.latLng,
      this.onMapCreated,
      this.initMarkerMap,
      this.selfLocationBack,
      this.initPolylinesMap});

  @override
  State<EMIGDMapWidget> createState() => _EMIGDMapWidgetState();
}

class _EMIGDMapWidgetState extends State<EMIGDMapWidget>
    with AMapLocationStateMixin {
  late CameraPosition kInitialPosition; //初始化镜头数据

  @override
  void initState() {
    super.initState();
    kInitialPosition = CameraPosition(
      target: widget.latLng ?? const LatLng(39.909187, 116.397451),
      zoom: 15.0,
    );
    // startLocation();
  }

  @override
  locationResultBack() {
    debugPrint('定位返回 ----  ');

    if (locationResult['latitude'] != null &&
        locationResult['longitude'] != null) {
      widget.selfLocationBack!((locationResult['latitude'] ?? 0) as double,
          (locationResult['longitude'] ?? 0) as double);
      stopLocation();
    }

    return super.locationResultBack();
  }

  @override
  Widget build(BuildContext context) {
    return AMapWidget(
        initialCameraPosition: kInitialPosition,
        buildingsEnabled: false,
        onMapCreated: onCreated,
        privacyStatement: const AMapPrivacyStatement(
            hasShow: true, hasAgree: true, hasContains: true),
        apiKey: AMapApiKey(
          iosKey: iosKey,
          androidKey: androidKey,
        ),
        polylines: Set<Polyline>.of(widget.initPolylinesMap?.values ?? []),
        markers: Set<Marker>.of(widget.initMarkerMap?.values ?? []));
  }

  void onCreated(AMapController controller) {
    AMapApprovalNumber.setApprovalNumber(controller); //图审号
    if (widget.onMapCreated != null) widget.onMapCreated!(controller);
  }

  @override
  String get androidKey => EMIMapConfig.androidKey;

  @override
  String get iosKey => EMIMapConfig.iosKey;
}
